package com.example.demo.executor;

import com.example.demo.entity.RelatedExecuteInformationEntity;
import com.example.demo.executor.backupDeal.BackupDealEnum;
import com.example.demo.executor.sqlGenerate.SqlGenerator;
import com.example.demo.executor.sqlGenerate.SqlGeneratorFactory;
import com.example.demo.typeEnums.ExecuteType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 又菜又爱浪
 * @date 2021-12
 * 关联的数据处理类
 */
@Component
public class RelatedTableExecutor implements Executor {

    @Autowired
    private SQLExecutor sqlExecutor;

    @Autowired
    private SqlGeneratorFactory sqlGeneratorFactory;

    @Value("${database.software.name}")
    private String databaseSoftwareName;

    public boolean execute(List<Object> executeConditions, RelatedExecuteInformationEntity relatedInformation){

        SqlGenerator sqlGenerator = sqlGeneratorFactory.getSqlGenerator(databaseSoftwareName);
        String executeType = ExecuteType.getExecuteType(relatedInformation.getExecuteType(), null).getName();
        String backupDealType = BackupDealEnum.getBackupDealType(relatedInformation.getBackupDealType());
        String tableName = relatedInformation.getTableName();

        if(executeConditions==null || executeConditions.size()==0){
            return false;
        }
        StringJoiner joiner = new StringJoiner(",");
        for(Object object : executeConditions){
            joiner.add(object.toString());
        }
        String condition = joiner.toString();
        // 得到跟主表与关联表的关联的字段名
        List<String> columns = new ArrayList<>();
        List<RelatedExecuteInformationEntity> relatedInfos = relatedInformation.getRelatedExecuteInformation();
        if(!CollectionUtils.isEmpty(relatedInfos)) {
            columns = relatedInfos.stream().filter(e -> StringUtils.isNotBlank(e.getParentColumn()))
                    .map(RelatedExecuteInformationEntity::getParentColumn).collect(Collectors.toList());
        }

        Map<String, List<Object>> params = new HashMap<>();
        if(columns.size()>0) {
            String paramQuerySql = sqlGenerator.generateAllParamQuerySql(tableName, columns,condition);
            params = sqlExecutor.queryRelatedParam(paramQuerySql,columns);
        }
        sqlExecutor.dataProcess(tableName,relatedInformation.getCurrentColumn(),executeConditions,executeType, backupDealType);
        // 执行关联的数据处理
        for(RelatedExecuteInformationEntity relatedInfo : relatedInfos){
            List<Object> conditions = params.get(relatedInfo.getParentColumn());
            this.execute(conditions,relatedInfo);
        }
        return false;
    }

}
